package com.base.commons.tools.utils;

import com.base.commons.tools.exception.BaseOfException;
import com.base.commons.tools.vo.DynamicColumnExportDTO;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ReflectionUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.beans.PropertyDescriptor;
import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;

public class DynamicCsvExportUtil {

    public static DecimalFormat decimalFormat = new DecimalFormat("0.00");

    /**
     * 下载导出的excel文件
     * @param exportDTO
     * @param response
     */
    public static void downloadFile(DynamicColumnExportDTO exportDTO, HttpServletResponse response){
        try {
            //生成csv文件流
            byte[] bytes = getCsvFile(exportDTO.getTitles(),
                    exportDTO.getColumnNames(),
                    exportDTO.getClazz(),
                    exportDTO.getSubTitles(),
                    exportDTO.getSubColumnNames(),
                    exportDTO.getSubClazz(),
                    exportDTO.getDataList());
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Type", "text/csv,charset=UTF-8");
            String fileName = String.valueOf(System.currentTimeMillis());
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".csv");
            ServletOutputStream out = response.getOutputStream();
            out.write(bytes);
            out.flush();
            out.close();
        } catch (IOException e) {
            throw new BaseOfException(e.getMessage());
        }
    }

    /**
     * 下载导出的excel文件
     * @param exportDTO
     * @param response
     */
    public static void downloadFileToLocalPath(DynamicColumnExportDTO exportDTO, HttpServletResponse response){
        try {
            //生成csv文件
            byte[] bytes = getCsvFile(exportDTO.getTitles(),
                    exportDTO.getColumnNames(),
                    exportDTO.getClazz(),
                    exportDTO.getSubTitles(),
                    exportDTO.getSubColumnNames(),
                    exportDTO.getSubClazz(),
                    exportDTO.getDataList());
            String filePath = "D:\\logs\\test1.csv";
            OutputStream out = new FileOutputStream(filePath);//文件保存地址
            out.write(bytes);
            out.flush();
            out.close();
        } catch (IOException e) {
            throw new BaseOfException(e.getMessage());
        }
    }

    /**
     * 导出Excel (支持一对多)
     *
     * @param titles      列标题列表
     * @param columnNames 待导出字段
     * @param clazz 数据对象类型
     * @param subTitles    子数据集合-列标题列表
     * @param subColumnNames 子数据集合-待导出字段
     * @param subClazz 子数据集合-数据对象类型
     * @param dataList    数据对象集合
     * @return
     */
    public static byte[] getCsvFile(List<String> titles, List<String> columnNames,Class<?> clazz,
                                             List<String> subTitles,List<String> subColumnNames, Class<?> subClazz,
                                             List dataList) {
        byte[] bytes = null;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try{
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out));
            //写入标题行
            createTitleRow(titles, subTitles,writer);
            //写入数据行
            createDataRow(columnNames, clazz, subColumnNames, subClazz, dataList,writer);

            bytes = out.toByteArray();
            writer.flush();
            writer.close();
        } catch(Exception e) {
            throw new BaseOfException("下载失败",e);
        }
        return bytes;
    }

    /**
     * 写入标题行
     * @param titles
     * @param subTitles
     */
    public static void createTitleRow(List<String> titles,List<String> subTitles,BufferedWriter writer) throws IOException{
        StringBuffer titleSubStr = new StringBuffer("");
        //创建列标题行
        for (int i = 0; i < titles.size(); i++) {
            if(i!=0){
                titleSubStr.append(",");
            }
            titleSubStr.append(titles.get(i));
        }

        //创建子集合列标题
        if (!CollectionUtils.isEmpty(subTitles)) {
            for(int n = 0; n < 10; n++) {
                for (int i = 0; i < subTitles.size(); i++) {
                    titleSubStr.append(",").append(subTitles.get(i));
                }
            }
        }

        titleSubStr.append("\n");
        writer.write(titleSubStr.toString());
    }

    /**
     * 写入数据行
     * @param columnNames
     * @param clazz
     * @param subColumnNames
     * @param subClazz
     * @param dataList
     */
    public static void createDataRow(List<String> columnNames,Class<?> clazz,
                                     List<String> subColumnNames, Class<?> subClazz,
                                     List dataList,BufferedWriter writer) throws Exception{
        if(!CollectionUtils.isEmpty(dataList)) {
            for (int k = 0; k < dataList.size(); k++) {
                StringBuffer dataSubStr = new StringBuffer("");
                Object data = dataList.get(k);
                //子集合数据字段
                List subDataList = null;
                if(subClazz!=null) {
                    Field subListField = clazz.getDeclaredField("subDataList");
                    subDataList = getListValueByField(clazz, data, subListField);
                }
                //遍历数据
                for (int i = 0; i < columnNames.size(); i++) {
                    //获取字段
                    Field field = clazz.getDeclaredField(columnNames.get(i));
                    String fieldValue = getStringValueByField(clazz, data, field);
                    //写入数据到单元格
                    if(i!=0){
                        dataSubStr.append(",");
                    }
                    dataSubStr.append(fieldValue);
                }

                int subNum = 0;
                if (!CollectionUtils.isEmpty(subColumnNames) && !CollectionUtils.isEmpty(subDataList)) {
                    for (int i = 0; i < subDataList.size(); i++) {
                        Object subData = subDataList.get(i);
                        //遍历子集合数据
                        for (int j = 0; j < subColumnNames.size(); j++) {
                            //获取字段
                            Field subField = subClazz.getDeclaredField(subColumnNames.get(j));
                            String subFieldValue = getStringValueByField(subClazz, subData, subField);
                            //写入数据到单元格
                            dataSubStr.append(",").append(subFieldValue);
                        }
                        subNum += subColumnNames.size();
                    }
                }

                dataSubStr.append("\n");
                writer.write(dataSubStr.toString());
            }
        }
    }

    public static String getStringValueByField(Class<?> clazz, Object data,Field field){
        String value = "";
        try {
            PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz);
            //获取get方法
            Method getMethod = pd.getReadMethod();
            Object fieldValue = ReflectionUtils.invokeMethod(getMethod, data);
            if (fieldValue == null) {
                fieldValue = "";
            } else {
                if (field.getType() == Date.class) {
                    fieldValue = DateUtils.format((Date) fieldValue, DateUtils.DATE_TIME_PATTERN);
                }
                if (field.getType() == BigDecimal.class) {
                    fieldValue = decimalFormat.format(fieldValue);
                }
            }

            value = fieldValue == null ? "" : fieldValue.toString();
        }catch (Exception e){
            throw new BaseOfException("获取字段值失败",e);
        }
        return value;
    }

    public static List getListValueByField(Class<?> clazz, Object data,Field field){
        List value = null;
        try {
            PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz);
            //获取get方法
            Method getMethod = pd.getReadMethod();
            Object fieldValue = ReflectionUtils.invokeMethod(getMethod, data);
            if (fieldValue != null) {
                value = (List)fieldValue;
            }
        }catch (Exception e){
            throw new BaseOfException("获取字段值失败",e);
        }
        return value;
    }
}
